library (gsubfn)
library (ggplot2)
library (directlabels)

#======================================================================

gen_ticks <- function (X, fun_tostep, fun_fromstep, xmin=NULL, xmax=NULL, stepjump=1) {
  first_step <- if (is.null (xmin)) floor (fun_tostep (min (X))) else fun_tostep (xmin)
  max_step <- if (is.null (xmax)) ceiling (fun_tostep (max (X))) else fun_tostep (xmax)
  fun_fromstep (seq (from=first_step, to=max_step, by=stepjump))
}

gen_ticks_linear <- function (X, stepsize, ...) {
  gen_ticks (X, fun_tostep=function (x) x / stepsize, fun_fromstep=function (x) x * stepsize, ...)
}

gen_ticks_log2 <- function (X, ...) {
  gen_ticks (X, fun_tostep=function (x) log2 (x), fun_fromstep=function (x) 2^x, ...)
}

gen_ticks_log10 <- function (X, ...) {
  gen_ticks (X, fun_tostep=function (x) log10 (x), fun_fromstep=function (x) 10^x, ...)
}

add_scale <- function (f_scale, name, ticks, ...) {
  f_scale (name=name, limits=c (min (ticks), max (ticks)), breaks=ticks, labels=ticks, ...)
}

setDevNarrow <- function () {
  if (dev.cur () != 1) dev.off ()
  dev.new (width=6 * 2 / 3, height=8 * 2 / 3)
}

setDevSquare <- function () {
  if (dev.cur () != 1) dev.off ()
  dev.new (width=6, height=6)
}

setDevSlide <- function (w=8, h=6) {
  if (dev.cur () != 1) dev.off ()
  dev.new (width=w, height=h) # Use these dimensions for slides
}

setDevHD <- function () {
  if (dev.cur () != 1) dev.off ()
  dev.new (width=(16/9)*6, height=6)  # Use these for HD format (for papers)
}


#======================================================================

genSigFigLabels <- function (X, k) {
  sapply (X, function (x) {
    if (x < 0 | x > 0) {
      l <- floor (log10 (abs (x)))
      if (k < l)
        y <- sprintf ("%d", signif (x, k))
      else # k >= l
        y <- sprintf (sprintf ("%%.%df", k-l-1), x)
    } else { # x == 0
      y <- sprintf (sprintf ("%%.%df", k-1))
    }
    return (y)
  })
}

#======================================================================
# eof
